package com.xjrsoft.module.erpModel.caseErpDevice.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.TypeReference;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.yulichang.toolkit.MPJWrappers;
import com.xjrsoft.common.annotation.XjrLog;
import com.xjrsoft.common.constant.GlobalConstant;
import com.xjrsoft.common.enums.YesOrNoEnum;
import com.xjrsoft.common.model.result.R;
import com.xjrsoft.common.page.ConventPage;
import com.xjrsoft.common.page.PageOutput;
import com.xjrsoft.common.utils.RedisUtil;
import com.xjrsoft.common.utils.VoToColumnUtil;
import com.xjrsoft.module.erpModel.caseErpDevice.dto.AddCaseErpDeviceInfoDto;
import com.xjrsoft.module.erpModel.caseErpDevice.dto.CaseErpDeviceInfoDto;
import com.xjrsoft.module.erpModel.caseErpDevice.dto.UpdateCaseErpDeviceInfoDto;
import com.xjrsoft.module.erpModel.caseErpDevice.entity.CaseErpDeviceInfo;
import com.xjrsoft.module.erpModel.caseErpDevice.service.ICaseErpDeviceInfoService;
import com.xjrsoft.module.erpModel.caseErpDevice.vo.CaseErpDeviceCodeInfo;
import com.xjrsoft.module.erpModel.caseErpDevice.vo.CaseErpDeviceInfoExportVo;
import com.xjrsoft.module.erpModel.caseErpDevice.vo.CaseErpDeviceInfoVo;
import com.xjrsoft.module.erpModel.caseErpSupplier.entity.CaseErpSupplier;
import com.xjrsoft.module.erpModel.caseErpSupplier.service.ICaseErpSupplierService;
import com.xjrsoft.module.organization.entity.User;
import com.xjrsoft.module.system.entity.DictionaryDetail;
import com.xjrsoft.module.system.service.IDictionarydetailService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.io.ByteArrayOutputStream;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 设备信息【case_erp_deviceinfo】 前端控制器
 * </p>
 *
 * @author hnyyzy
 * @since 2023-06-21
 */
@RestController
@RequestMapping(GlobalConstant.CASE_ERP_DEVICE +"/caseErpDeviceInfo")
@Api(value = GlobalConstant.CASE_ERP_DEVICE +"/caseErpDeviceInfo", tags = "设备信息")
@AllArgsConstructor
public class CaseErpDeviceInfoController {

    private ICaseErpDeviceInfoService caseErpDeviceInfoService;

    private ICaseErpSupplierService caseErpSupplierService;

    private IDictionarydetailService dictionarydetailService;

    private RedisUtil redisUtil;

    @GetMapping(value = "/page")
    @ApiOperation("设备信息分页")
    public R page(CaseErpDeviceInfoDto dto) {
        IPage<CaseErpDeviceInfoVo> page = caseErpDeviceInfoService.selectJoinListPage(ConventPage.getPage(dto), CaseErpDeviceInfoVo.class,
                MPJWrappers.<CaseErpDeviceInfo>lambdaJoin()
                        .distinct()
                        .orderByDesc(CaseErpDeviceInfo::getCreateDate)
                        .eq(ObjectUtil.isNotEmpty(dto.getTypeId()),CaseErpDeviceInfo::getTypeId,dto.getTypeId())
                        .eq(StrUtil.isNotBlank(dto.getName()),CaseErpDeviceInfo::getName,dto.getName())
                        .eq(StrUtil.isNotBlank(dto.getAddress()),CaseErpDeviceInfo::getAddress,dto.getAddress())
                        .selectAs(CaseErpSupplier::getName, CaseErpDeviceInfoVo::getSupplierName)
                        .selectAs(DictionaryDetail::getName,CaseErpDeviceInfoVo::getTypeName)
                        .select(CaseErpDeviceInfo::getId)
                        .select(CaseErpDeviceInfo.class, x -> VoToColumnUtil.fieldsToColumns(CaseErpDeviceInfoVo.class).contains(x.getProperty()))
                        .leftJoin(CaseErpSupplier.class, CaseErpSupplier::getId, CaseErpDeviceInfo::getSupplierId)
                        .leftJoin(DictionaryDetail.class,DictionaryDetail::getId,CaseErpDeviceInfo::getTypeId));

        PageOutput<CaseErpDeviceInfoVo> pageOutput = ConventPage.getPageOutput(page);
        return R.ok(pageOutput);
    }

    @PostMapping
    @ApiOperation(value = "新增设备信息")
    public R add(@Valid @RequestBody AddCaseErpDeviceInfoDto dto) {
        long count = caseErpDeviceInfoService.count(Wrappers.<CaseErpDeviceInfo>query().lambda().eq(CaseErpDeviceInfo::getName, dto.getName()));
        if (count > 0) {
            return R.error("此设备已经存在！");
        }
        CaseErpDeviceInfo caseErpDeviceInfo = BeanUtil.toBean(dto, CaseErpDeviceInfo.class);
        caseErpDeviceInfo.setState(YesOrNoEnum.YES.getCode());
        List<User> allUser = redisUtil.get(GlobalConstant.USER_CACHE_KEY, new TypeReference<List<User>>() {
        });
        String allUserIdStr = StrUtil.join(StringPool.COMMA, dto.getPrincipalIds());
        List<Long> ids = Arrays.stream(allUserIdStr.split(StringPool.COMMA)).map(Convert::toLong).collect(Collectors.toList());
        List<String> names = allUser.stream().filter(x -> ids.contains(x.getId())).map(User::getName).collect(Collectors.toList());
        caseErpDeviceInfo.setPrincipalNames(StrUtil.join(StringPool.COMMA,names));
        caseErpDeviceInfoService.save(caseErpDeviceInfo);
        return R.ok(true);
    }

    @PutMapping
    @ApiOperation(value = "修改设备信息")
    public R update(@Valid @RequestBody UpdateCaseErpDeviceInfoDto dto) {
        CaseErpDeviceInfo caseErpDeviceInfo = BeanUtil.toBean(dto, CaseErpDeviceInfo.class);
        List<User> allUser = redisUtil.get(GlobalConstant.USER_CACHE_KEY, new TypeReference<List<User>>() {
        });
        String allUserIdStr = StrUtil.join(StringPool.COMMA, dto.getPrincipalIds());
        List<Long> ids = Arrays.stream(allUserIdStr.split(StringPool.COMMA)).map(Convert::toLong).collect(Collectors.toList());
        List<String> names = allUser.stream().filter(x -> ids.contains(x.getId())).map(User::getName).collect(Collectors.toList());
        caseErpDeviceInfo.setPrincipalNames(StrUtil.join(StringPool.COMMA,names));
        caseErpDeviceInfoService.updateById(caseErpDeviceInfo);
        return R.ok(true);
    }

    @GetMapping(value = "/info")
    @ApiOperation(value = "根据id查询设备信息")
    public R info(@RequestParam Long id) {
        CaseErpDeviceInfo caseErpDeviceInfo = caseErpDeviceInfoService.getById(id);
        if (caseErpDeviceInfo == null) {
            R.error("找不到此设备！");
        }
        return R.ok(BeanUtil.toBean(caseErpDeviceInfo, CaseErpDeviceCodeInfo.class));
    }

    @GetMapping(value = "/check")
    @ApiOperation(value = "根据id查看设备信息")
    public R check(@RequestParam Long id) {
        CaseErpDeviceInfo caseErpDeviceInfo = caseErpDeviceInfoService.getById(id);
        if (caseErpDeviceInfo == null) {
            R.error("找不到此设备！");
        }
        CaseErpDeviceInfoVo caseErpDeviceInfoVo = BeanUtil.toBean(caseErpDeviceInfo, CaseErpDeviceInfoVo.class);
        String supplierName = caseErpSupplierService.getById(caseErpDeviceInfo.getSupplierId()).getName();
        caseErpDeviceInfoVo.setSupplierName(supplierName);
        String typeName = dictionarydetailService.getById(caseErpDeviceInfo.getTypeId()).getName();
        caseErpDeviceInfoVo.setTypeName(typeName);
        return R.ok(caseErpDeviceInfoVo);
    }

    @DeleteMapping
    @ApiOperation(value = "删除设备信息")
    @XjrLog(value = "删除设备信息")
    public R delete(@Valid @RequestBody Long id) {
        return R.ok(caseErpDeviceInfoService.removeById(id));
    }

    @PostMapping(value = "/export")
    @ApiOperation(value = "导出")
    @XjrLog(value = "导出表单数据")
    public ResponseEntity<byte[]> export(@RequestBody List<Long> ids) {
        List<CaseErpDeviceInfoExportVo> caseErpDeviceInfoVoList = caseErpDeviceInfoService.selectJoinList(CaseErpDeviceInfoExportVo.class,
                MPJWrappers.<CaseErpDeviceInfo>lambdaJoin()
                        .distinct()
                        .in(CaseErpDeviceInfo::getId, ids)
                        .selectAs(CaseErpSupplier::getName, CaseErpDeviceInfoExportVo::getSupplierName)
                        .selectAs(DictionaryDetail::getName,CaseErpDeviceInfoExportVo::getTypeName)
                        .select(CaseErpDeviceInfo::getId)
                        .select(CaseErpDeviceInfo.class, x -> VoToColumnUtil.fieldsToColumns(CaseErpDeviceInfoExportVo.class).contains(x.getProperty()))
                        .leftJoin(CaseErpSupplier.class, CaseErpSupplier::getId, CaseErpDeviceInfo::getSupplierId)
                        .leftJoin(DictionaryDetail.class,DictionaryDetail::getId,CaseErpDeviceInfo::getTypeId));
        ByteArrayOutputStream bot = new ByteArrayOutputStream();
        EasyExcel.write(bot, CaseErpDeviceInfoExportVo.class).excelType(ExcelTypeEnum.XLSX).sheet().doWrite(caseErpDeviceInfoVoList);
        return R.fileStream(bot.toByteArray(), "设备信息" + ExcelTypeEnum.XLSX.getValue());
    }

    @GetMapping(value = "/get-by-type-id")
    @ApiOperation(value = "根据typeId查询相关设备信息")
    public R getByTypeId(@RequestParam Long typeId) {
        List<CaseErpDeviceInfo> caseErpDeviceInfoList = caseErpDeviceInfoService.list(Wrappers.<CaseErpDeviceInfo>query().lambda().eq(CaseErpDeviceInfo::getTypeId, typeId));
        List<CaseErpDeviceCodeInfo> caseErpDeviceInfoVoList = BeanUtil.copyToList(caseErpDeviceInfoList, CaseErpDeviceCodeInfo.class);
        return R.ok(caseErpDeviceInfoVoList);
    }


}
